//
//  ViewController.swift
//  vmes
//
//  Created by user on 2021/10/22.
//

import UIKit
import SnapKit
import Alamofire
import Toast

class ViewController: BaseController, UITextFieldDelegate {
    
    //    var usernameTxt:UITextField?
    let usernameTxt=UITextField()
    let pwdTxt=UITextField()
    //底部登录view
    let layerView = UIView()
    
    //多单开工按钮
    lazy var rememberBtn: UIButton = {
        let btn = UIButton()
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        btn.setTitle("  记住我", for: .normal)
        let icon_unselect =  UIImage (named: "icon_choose_unselect" )?.withRenderingMode(.alwaysOriginal)
        let icon_select =  UIImage (named: "icon_choose_select" )?.withRenderingMode(.alwaysOriginal)
        btn.setTitleColor(UIColor.black, for: .normal)
        btn.setImage(icon_unselect,  for :.normal)
        btn.setImage(icon_select,  for :.selected)
        btn.addTarget(self, action: #selector(rememberme), for: .touchUpInside)
        return btn
    }()
    
    @objc func rememberme(){
        rememberBtn.isSelected = !rememberBtn.isSelected
        defaults.set(rememberBtn.isSelected, forKey: "remember")
    }
    
    let defaults = UserDefaults.standard
    
    override func viewWillAppear(_ animated: Bool) {
        navigationController?.setNavigationBarHidden(true, animated: false)
        rememberBtn.isSelected=defaults.bool(forKey: "remember")
        if rememberBtn.isSelected{
            usernameTxt.text=defaults.string(forKey: "username")
            pwdTxt.text=defaults.string(forKey: "pwd")
        }else{
            pwdTxt.text=""
            usernameTxt.text=""
        }
        detectionOfUpdate()
    }
    
    func saveUser(username:String,pwd:String){
        if rememberBtn.isSelected{
            defaults.set(username, forKey: "username")
            defaults.set(pwd, forKey: "pwd")
        }else{
            defaults.set("", forKey: "username")
            defaults.set("", forKey: "pwd")
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        //设置渐变背景色
        let backgroundView = UIView()
        backgroundView.frame=UIScreen.main.bounds;
        //        layerView.frame = CGRect(x: 0, y: 0, width: 375, height: 667)
        // fillCode
        let backColor = CAGradientLayer()
        backColor.colors = [UIColor(red: 0.06, green: 0.64, blue: 0.53, alpha: 1).cgColor, UIColor(red: 0.06, green: 0.64, blue: 0.53, alpha: 0).cgColor]
        backColor.locations = [0, 1];
        backColor.frame = backgroundView.bounds;
        backColor.startPoint = CGPoint(x: 1, y: 0)
        backColor.endPoint = CGPoint(x: 1, y: 1)
        backgroundView.layer.addSublayer(backColor)
        view.addSubview(backgroundView)
        let imageView=UIImageView(image: UIImage(named: "login_logo"))
        view.addSubview(imageView)
        imageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(statusBarHeight)
        }
        
        layerView.backgroundColor=UIColor.white
        layerView.layer.cornerRadius=6
        backgroundView.addSubview(layerView)
        layerView.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.top.equalTo(imageView.snp.bottom).offset(50)
        }
        let title=UILabel()
        title.text="设备上云-操作端 v1.0"
        title.textColor=UIColor.colorWithHex(hexStr: "#333333")
        title.font = UIFont.systemFont(ofSize: 22)
        layerView.addSubview(title)
        title.snp.makeConstraints { make in
            make.centerX.equalTo(layerView.snp.centerX)
            make.top.equalToSuperview().offset(30)
        }
        
        layerView.addSubview(usernameTxt)
        usernameTxt.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.top.equalTo(title.snp.bottom).offset(50)
            make.width.equalTo(200)
            make.height.equalTo(50)
        }
        usernameTxt.borderStyle=UITextField.BorderStyle.roundedRect
        usernameTxt.placeholder = "用户名"// 提示语
        usernameTxt.delegate = self
        usernameTxt.returnKeyType = .done
//        usernameTxt.resignFirstResponder()
        pwdTxt.delegate=self
        pwdTxt.returnKeyType = .done
        //        usernameTxt.text="WS002"
        layerView.addSubview(pwdTxt)
        pwdTxt.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.top.equalTo(usernameTxt.snp.bottom).offset(20)
            make.width.equalTo(200)
            make.height.equalTo(50)
        }
        pwdTxt.borderStyle=UITextField.BorderStyle.roundedRect
        pwdTxt.placeholder = "密码"// 提示语
        //        pwdTxt.text="123456"
        //        let loginBtn=UIButton(type: .custom)
        layerView.addSubview(rememberBtn)
        rememberBtn.snp.makeConstraints { make in
            make.left.equalTo(pwdTxt.snp.left)
            make.top.equalTo(pwdTxt.snp.bottom).offset(10)
        }
        let button = UIButton(type: .custom)
        layerView.addSubview(button)
        button.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.top.equalTo(rememberBtn.snp.bottom).offset(20)
            make.height.equalTo(50)
        }
        button.setTitle("登录", for: .normal)
        button.backgroundColor = UIColor.colorWithHex(hexStr: "#0FA386")
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
        button.setTitleColor(UIColor.colorWithHex(hexStr: "#ffffff"), for: .normal)
        button.addTarget(self, action: #selector(didClickLoginButton), for: .touchUpInside)
        
        let verisonLabel=UILabel()
        verisonLabel.text="版本日期：2022-5-1"
        layerView.addSubview(verisonLabel)
        verisonLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(button.snp.bottom).offset(10)
        }
        
        usernameTxt.returnKeyType = .done
        pwdTxt.returnKeyType = .done
        pwdTxt.isSecureTextEntry = true
        initLoadingView()
        
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
//    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
//        if text == "\n" {
//            textView.resignFirstResponder()
//            return false
//        }
//        return true
//    }
    
    @objc func didClickLoginButton() {
        //       ZhiFuBaoStyle()
//        navigationController?.pushViewController(WorkQualityController(), animated: true)
        doLogin()
    }
    
    func toMain(){
        let mainVC = LeaderController()
        mainVC.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(mainVC, animated: true)
        //        let mainStoryboard = UIStoryboard(name: "LaunchScreen", bundle: nil)
        //        let navc = mainStoryboard.instantiateViewController(withIdentifier: "NavController") as! UINavigationController
        //        navc.pushViewController(mainVC, animated: true)
        //        self.present(mainVC, animated: true, completion: nil)
    }
    
    func doLogin(){
        print("kaishi请求")
        spinner.startAnimating()
        let name=(String)(usernameTxt.text ?? "")
        let pwd=(String)(pwdTxt.text ?? "")
        saveUser(username: name , pwd: pwd)
        let parameters: Dictionary = ["username" : usernameTxt.text,"password":pwdTxt.text]
        sessionManager.request(NetInfo.loginUrl, method:.post
                               , parameters:parameters,encoder: JSONParameterEncoder.default,requestModifier: { $0.timeoutInterval = 10 }).responseJSON { (response) in
            self.spinner.stopAnimating()
            print(response)
            switch response.result {
            case .success:
                if let data=response.data{
                    let response = try? JSONDecoder().decode(LoginInfo.self, from: data)
                    if(response?.code==200){
                        K.userInfo=response?.data?.userInfo
                        K.headers=[
                            "Authorization": "Bearer "+(response?.data?.access_token)!,
                            "Accept": "application/json"
                        ]
                        if ("9999" != K.userInfo?.post?.postCode) {  //9999操作工 非9999 全部跳lead页面
                            self.toMain()
                        }else{
                            let mainVC = MainController()
                            mainVC.hidesBottomBarWhenPushed = true
                            self.navigationController?.pushViewController(mainVC, animated: true)
                        }
                        
                    }else{
                        self.view.makeToast(response?.msg)
                    }
                }
            case .failure:
                print("ERROR")
                self.view.makeToast("请求失败")
            }
        }
    }
}

